/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.xn.snakegame;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.example.xn.snakegame.MainActivity.orication;



/**
 * SnakeView: implementation of a simple game of Snake
 * 
 * 
 */
public class SnakeView extends TileView implements orication{
    //弹框信息数组
    String items[]=new String[]{"30秒吃掉8个","60秒吃掉18个","90秒吃掉25个"};
    int item;
    boolean ispause=false;
    boolean ischoose;
    boolean ishead=false;
    boolean isfirst=true;
    private static final String TAG = "SnakeView";
    Coordinate head ;
    Coordinate newHead;
    int RandomNumber;
    /**
     * Current mode of application: READY to run, RUNNING, or you have already
     * lost. static final ints are used instead of an enum for performance
     * reasons.
     */
    private int mMode = READY;
    private  int oldMode ;
    public static final int PAUSE = 0;
    public static final int READY = 1;
    public static final int RUNNING = 2;
    public static final int LOSE = 3;

    /**
     * Current direction the snake is headed.
     */
    private int mDirection = NORTH;
    private int mNextDirection = NORTH;
    private static final int NORTH = 1;
    private static final int SOUTH = 2;
    private static final int EAST = 3;
    private static final int WEST = 4;

    /**
     * Labels for the drawables that will be loaded into the TileView class
     */
    private static final int RED_STAR = 1;
    private static final int YELLOW_STAR = 2;
    private static final int GREEN_STAR = 3;

    /**
     * mScore: used to track the number of apples captured mMoveDelay: number of
     * milliseconds between snake movements. This will decrease as apples are
     * captured.
     */
    private int oldertime;
    private long mScore = 0;
    private long mMoveDelay = 100;
    /**
     * mLastMove: tracks the absolute time when the snake last moved, and is used
     * to determine if a move should be made based on mMoveDelay.
     */
    private long mLastMove;
    
    /**
     * mStatusText: text shows to the user in some run states
     */
    private TextView mStatusText;

    /**
     * mSnakeTrail: a list of Coordinates that make up the snake's body
     * mAppleList: the secret location of the juicy apples the snake craves.
     */
    //qingtishuzu
    private ArrayList<Coordinate> mSnakeTrail = new ArrayList<Coordinate>();
    private ArrayList<Coordinate> mAppleList = new ArrayList<Coordinate>();
    private ArrayList<Coordinate> mWallList=new ArrayList<Coordinate>();
    private ArrayList<Coordinate> mWallList2=new ArrayList<>();
    private ArrayList<Coordinate> mWallList3=new ArrayList<>();
    ArrayList [] Mwall=new ArrayList[3];

    /**
     * Everyone needs a little randomness in their life
     */
    private static final Random RNG = new Random();
//倒计时更新
    Timer timer;
    Message message;
    class myTimetask extends TimerTask{

        @Override
        public void run() {
//            if(MainActivity.time<=0)
//            {
//
//                // timehander.sendMessage(message);
//                //timer.cancel();
//                //timehander.sendMessage(Message.obtain());
////                message=Message.obtain();
////                message.what=2;
////                timehander.sendMessage(message);
//
//            }else
//            {
//
//                timehander.sendMessage(Message.obtain());
//
//            }
            timehander.sendMessage(Message.obtain());
        }
    };
    myTimetask mytask;
    Handler timehander=new Handler(){
    @Override
    public void handleMessage(Message msg) {
if(msg.what==1)
{
    timer.cancel();
   timehander.removeMessages(1);

}
else if(msg.what==2)
{
    setMode(LOSE);
}
else {

    MainActivity.time_text.setText(MainActivity.time + "");
    if(MainActivity.time<=10)
    {
        if(MainActivity.timeText.getVisibility()==View.INVISIBLE) {
            MainActivity.timeText.setVisibility(VISIBLE);
            MainActivity.params.setMargins(MainActivity.mSnakeView.getWidth()/2,30,0,0);
            MainActivity.timeText.setLayoutParams(MainActivity.params);
        }
        MainActivity.timeText.setText(MainActivity.time+"");
    };
    if(MainActivity.time==0)
    {
        setMode(LOSE);
    }
    else {
        MainActivity.time--;
    }
}
    }
};

    /**
     * Create a simple handler that we can use to cause animation to happen.  We
     * set ourselves as a target and we can use the sleep()
     * function to cause an update/invalidate to occur at a later date.
     */
    private RefreshHandler mRedrawHandler = new RefreshHandler();

    @Override
    public void orderorication(int Direction) {
        if(Direction==1&&!ispause)
          {
              if(mDirection!=SOUTH)
              mNextDirection=NORTH;
          }
        if(Direction==2&&!ispause)
        {
            if(mDirection!=NORTH)
            mNextDirection=SOUTH;
        }
        if(Direction==3&&!ispause)
        {
            if(mDirection!=WEST)
                mNextDirection=EAST;
        }
        if(Direction==4&&!ispause)
        {
            if(mDirection!=EAST)
            {
                mNextDirection=WEST;
            }
        }
        if(Direction==0)
        {
            if(!ispause) {

                setMode(PAUSE);

                ishead=true;
            }
            else{
                MainActivity.btn_pause.setImageResource(R.drawable.start);
                setMode(RUNNING);
                //update();
                ispause=false;
                mytask=new myTimetask();
                timer.schedule(mytask,0,1000);
            }
        }
    }
    class RefreshHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            SnakeView.this.invalidate();
            SnakeView.this.update();

        }

        public void sleep(long delayMillis) {
            this.removeMessages(0);
            if(isfirst)
            {
                sendMessage(Message.obtain());
                isfirst=false;
            }
        	else
            {
                sendMessageDelayed(obtainMessage(0), delayMillis);
            }

        }
    };


    /**
     * Constructs a SnakeView based on inflation from XML
     * 
     * @param context
     * @param attrs
     */
    public SnakeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSnakeView();
        Log.d("oncreate","1111");
   }

    public SnakeView(Context context, AttributeSet attrs, int defStyle) {
    	super(context, attrs, defStyle);
    	initSnakeView();

    }

    private void initSnakeView() {
        setFocusable(true);
        Resources r = this.getContext().getResources();
        resetTiles(4);
        loadTile(RED_STAR, r.getDrawable(R.drawable.redstar));
        loadTile(YELLOW_STAR, r.getDrawable(R.drawable.yellowstar1));
        loadTile(GREEN_STAR, r.getDrawable(R.drawable.greenstar));
        Mwall[0]=mWallList;
        Mwall[1]=mWallList2;
        Mwall[2]=mWallList3;

    }
    public void initNewGame() {

        mSnakeTrail.clear();
        mAppleList.clear();

        // For now we're just going to load up a short default eastbound snake
        // that's just turned north

        
        mSnakeTrail.add(new Coordinate(7, 7));
        mSnakeTrail.add(new Coordinate(6, 7));
        mSnakeTrail.add(new Coordinate(5, 7));
        mSnakeTrail.add(new Coordinate(4, 7));
        mSnakeTrail.add(new Coordinate(3, 7));
        mSnakeTrail.add(new Coordinate(2, 7));
        mNextDirection = EAST;
        for(int i=0;i<7;i++)
        {

            //setTile(GREEN_STAR,9,9+i);
            Coordinate coordinateleft=new Coordinate(9,(mYTileCount-9)/2+i);
            mWallList.add(coordinateleft);
           // setTile(GREEN_STAR,mXTileCount-9,9+i);
            Coordinate coordinateright=new Coordinate(mXTileCount-9,(mYTileCount-9)/2+i);
            mWallList.add(coordinateright);
        }
        for(int i=0;i<7;i++)
        {

            Coordinate coordinateup=new Coordinate((mXTileCount-7)/2+i,8);
            mWallList2.add(coordinateup);
            Coordinate coordinatedown=new Coordinate((mXTileCount-7)/2+i,mYTileCount-8);
            mWallList2.add(coordinatedown);
        }
        for(int i=0;i<7;i++)
        {
            Coordinate coordinateCenter=new Coordinate((mXTileCount-7)/2+i,mYTileCount/2);
            mWallList3.add(coordinateCenter);
        }
        // Two apples to start with
        RandomNumber=RNG.nextInt(3);
        addRandomApple();
        addRandomApple();
        mMoveDelay = 300;
        mScore = 0;
        oldertime=MainActivity.time;
        timer=new Timer();
        mytask=new myTimetask();
        timer.schedule(mytask, 0, 1000);

    }
    /**
     * Given a ArrayList of coordinates, we need to flatten them into an array of
     * ints before we can stuff them into a map for flattening and storage.
     * 
     * @param cvec : a ArrayList of Coordinate objects
     * @return : a simple array containing the x/y values of the coordinates
     * as [x1,y1,x2,y2,x3,y3...]
     */
//    private int[] coordArrayListToArray(ArrayList<Coordinate> cvec) {
//        int count = cvec.size();
//        int[] rawArray = new int[count * 2];
//        for (int index = 0; index < count; index++) {
//            Coordinate c = cvec.get(index);
//            rawArray[2 * index] = c.x;
//            rawArray[2 * index + 1] = c.y;
//        }
//        return rawArray;
//    }

    /**
     * Save game state so that the user does not lose anything
     * if the game process is killed while we are in the 
     * background.
     * 
     * @return a Bundle with this view's state
     */
//    public Bundle saveState() {
//        Bundle map = new Bundle();
//        map.putIntArray("mAppleList", coordArrayListToArray(mAppleList));
//        map.putInt("mDirection", Integer.valueOf(mDirection));
//        map.putInt("mNextDirection", Integer.valueOf(mNextDirection));
//        map.putLong("mMoveDelay", Long.valueOf(mMoveDelay));
//        map.putLong("mScore", Long.valueOf(mScore));
//        map.putIntArray("mSnakeTrail", coordArrayListToArray(mSnakeTrail));
//        return map;
  //  }

    /**
     * Given a flattened array of ordinate pairs, we reconstitute them into a
     * ArrayList of Coordinate objects
     * 
     * @param rawArray : [x1,y1,x2,y2,...]
     * @return a ArrayList of Coordinates
     */
    private ArrayList<Coordinate> coordArrayToArrayList(int[] rawArray) {
        ArrayList<Coordinate> coordArrayList = new ArrayList<Coordinate>();
        int coordCount = rawArray.length;
        for (int index = 0; index < coordCount; index += 2) {
            Coordinate c = new Coordinate(rawArray[index], rawArray[index + 1]);
            coordArrayList.add(c);
        }
        return coordArrayList;
    }

    /**
     * Restore game state if our process is being relaunched
     * 
     * @param icicle a Bundle containing the game state
     */
    public void restoreState(Bundle icicle) {
        setMode(PAUSE);
        mAppleList = coordArrayToArrayList(icicle.getIntArray("mAppleList"));
        mDirection = icicle.getInt("mDirection");
        mNextDirection = icicle.getInt("mNextDirection");
        mMoveDelay = icicle.getLong("mMoveDelay");
        mScore = icicle.getLong("mScore");
        mSnakeTrail = coordArrayToArrayList(icicle.getIntArray("mSnakeTrail"));
    }

    /*
     * handles key events in the game. Update the direction our snake is traveling
     * based on the DPAD. Ignore events that would cause the snake to immediately
     * turn back on itself.
     * 
     * (non-Javadoc)
     * 
     * @see android.view.View#onKeyDown(int, android.os.KeyEvent)
     */
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent msg) {
//
//        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
//            if (mMode == READY | mMode == LOSE) {
//                /*
//                 * At the beginning of the game, or the end of a previous one,
//                 * we should start a new game.
//                 */
//
//                initNewGame();
//                setMode(RUNNING);
//                update();
//                return (true);
//            }
//
//            if (mMode == PAUSE) {
//                /*
//                 * If the game is merely paused, we should just continue where
//                 * we left off.
//                 */
//                setMode(RUNNING);
//                update();
//                return (true);
//            }
//
//            if (mDirection != SOUTH) {
//                mNextDirection = NORTH;
//            }
//            return (true);
//        }
//
//        if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
//            if (mDirection != NORTH) {
//                mNextDirection = SOUTH;
//            }
//            return (true);
//        }
//
//        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
//            if (mDirection != EAST) {
//                mNextDirection = WEST;
//            }
//            return (true);
//        }
//
//        if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
//            if (mDirection != WEST) {
//                mNextDirection = EAST;
//            }
//            return (true);
//        }
//
//        return super.onKeyDown(keyCode, msg);
//    }

    /**
     * Sets the TextView that will be used to give information (such as "Game
     * Over" to the user.
     * 
     * @param newView
     */
    public void setTextView(TextView newView) {
        mStatusText = newView;
    }

    /**
     * Updates the current mode of the application (RUNNING or PAUSED or the like)
     * as well as sets the visibility of textview for notification
     * 
     * @param newMode
     */
    public void setMode(int newMode) {
         oldMode = mMode;
        mMode = newMode;
        if (newMode == RUNNING & oldMode != RUNNING) {
            if(!MygameApplication.mediaPlayer.isPlaying())
            {
                MygameApplication.mediaPlayer.start();
            }
            mStatusText.setVisibility(View.INVISIBLE);
            MygameApplication.mediaPlayer.start();
            update();
            return;
        }

        Resources res = getContext().getResources();
        CharSequence str = "";
        if (newMode == PAUSE) {
            MygameApplication.mediaPlayer.pause();
            mytask.cancel();
            MainActivity.btn_pause.setImageResource(R.drawable.pause2);
            ispause = true;

           // Intent intent=new Intent()
//            mStatusText.setVisibility(View.INVISIBLE);
//            str = res.getText(R.string.mode_pause);
        }
        if (newMode == READY) {
            str = res.getText(R.string.mode_ready);
            mStatusText.setText(str);
            mStatusText.setVisibility(View.VISIBLE);

        }
        if (newMode == LOSE) {
            message=Message.obtain();
            message.what=1;
            timehander.sendMessage(message);
//            str = res.getString(R.string.mode_lose_prefix) + mScore
//                  + res.getString(R.string.mode_lose_suffix);
           // timer.cancel();
            showDialog();
        }
    }

    /**
     * Selects a random location within the garden that is not currently covered
     * by the snake. Currently _could_ go into an infinite loop if the snake
     * currently fills the garden, but we'll leave discovery of this prize to a
     * truly excellent snake-player.
     * 
     */
    private void addRandomApple() {
        Coordinate newCoord = null;
        boolean found = false;
        while (!found) {
            // Choose a new location for our apple
            int newX = 1 + RNG.nextInt(mXTileCount - 2);
            int newY = 1 + RNG.nextInt(mYTileCount - 2);
            newCoord = new Coordinate(newX, newY);
            // Make sure it's not already under the snake
            boolean collision = false;
            int snakelength = mSnakeTrail.size();
            ArrayList<Coordinate> list=Mwall[RandomNumber];
            for (int index = 0; index < snakelength; index++) {
                if (mSnakeTrail.get(index).equals(newCoord)||list.get(index).equals(newCoord)) {
                    collision = true;
                }
            }

            // if we're here and there's been no collision, then we have
            // a good location for an apple. Otherwise, we'll circle back
            // and try again
            found = !collision;
        }
        if (newCoord == null) {
            Log.e(TAG, "Somehow ended up with a null newCoord!");
        }
        mAppleList.add(newCoord);
    }


    /**
     * Handles the basic update loop, checking to see if we are in the running
     * state, determining if a move should be made, updating the snake's location.
     */
    public void update() {
        if (mMode == RUNNING) {
            long now = System.currentTimeMillis();
            if (now - mLastMove >= mMoveDelay) {
                clearTiles();
                updateWalls();
                updateSnake();
                updateApples();
                mLastMove = now;
           }
            mRedrawHandler.sleep(mMoveDelay);
        }


    }

    /**
     * Draws some walls.
     * 
     */
    private void updateWalls() {
        for (int x = 0; x < mXTileCount; x++) {
            setTile(GREEN_STAR, x, 0);
            setTile(GREEN_STAR, x, mYTileCount - 1);
        }
        for (int y = 1; y < mYTileCount - 1; y++) {
            setTile(GREEN_STAR, 0, y);
            setTile(GREEN_STAR, mXTileCount - 1, y);
        }


for(int i=0;i<Mwall[RandomNumber].size();i++)
{
    Coordinate coordinate= (Coordinate) Mwall[RandomNumber].get(i);

    setTile(GREEN_STAR,coordinate.getX(),coordinate.getY());

}

//        for(int i=0;i<7;i++)
//        {
//
//          setTile(GREEN_STAR,9,(mYTileCount-9)/2+i);
//
//            setTile(GREEN_STAR,mXTileCount-9,(mYTileCount-9)/2+i);
//
//        }


    }

    /**
     * Draws some apples.
     * 
     */
    private void updateApples() {
        for (Coordinate c : mAppleList) {
            setTile(YELLOW_STAR, c.x, c.y);
        }
    }

    /**
     * Figure out which way the snake is going, see if he's run into anything (the
     * walls, himself, or an apple). If he's not going to die, we then add to the
     * front and subtract from the rear in order to simulate motion. If we want to
     * grow him, we don't subtract from the rear.
     * 
     */
    private void updateSnake() {
        boolean growSnake = false;
        // grab the snake by the head
         head = mSnakeTrail.get(0);
         newHead = new Coordinate(1, 1);
        mDirection = mNextDirection;

            switch (mDirection) {
                case EAST: {

                        newHead = new Coordinate(head.x + 1, head.y);

                    break;
                }
                case WEST: {

                        newHead = new Coordinate(head.x - 1, head.y);

                    break;
                }
                case NORTH: {

                        newHead = new Coordinate(head.x, head.y - 1);
                    break;
                }
                case SOUTH: {

                        newHead = new Coordinate(head.x, head.y + 1);

                    break;
                }
            }
        Log.d("head",head.x+"1111"+head.y);
      //碰到墙壁
        // Collision detection
        // For now we have a 1-square wall around the entire arena
        if ((newHead.x < 1) || (newHead.y < 1) || (newHead.x > mXTileCount - 2)
                || (newHead.y > mYTileCount - 2)) {
            setMode(LOSE);
            return;

        }
       ArrayList<Coordinate> list=Mwall[RandomNumber];
        int length=list.size();
        for(int i=0;i<length;i++)
        {
            if(list.get(i).equals(newHead)) {
                setMode(LOSE);
                return;
            }
        }
      //碰到自己
        // Look for collisions with itself
        int snakelength = mSnakeTrail.size();
        for (int snakeindex = 0; snakeindex < snakelength; snakeindex++) {
            Coordinate c = mSnakeTrail.get(snakeindex);
            if (c.equals(newHead)) {
                setMode(LOSE);
                return;
            }
        }

        // Look for apples
        int applecount = mAppleList.size();
        for (int appleindex = 0; appleindex < applecount; appleindex++) {
            Coordinate c = mAppleList.get(appleindex);
            if (c.equals(newHead)) {
                mAppleList.remove(c);
                addRandomApple();
                mScore++;
                MainActivity.score.setText(mScore+"");
                mMoveDelay *= 0.9;
                growSnake = true;
            }
        }

        // push a new head onto the ArrayList and pull off the tail
        if(ishead)
        {
            //ishead=false;
        }else {
            mSnakeTrail.add(0, newHead);
        }
        // except if we want the snake to grow

        if (!growSnake&&!ishead) {
            mSnakeTrail.remove(mSnakeTrail.size() - 1);

        }else if(!growSnake&&ishead)
        {
            ishead=false;
        }
        int index = 0;
        for (Coordinate c : mSnakeTrail) {
            if (index == 0) {
                setTile(YELLOW_STAR, c.x, c.y);
            } else {
                setTile(RED_STAR, c.x, c.y);
            }
            index++;
        }

    }

    /**
     * Simple class containing two integer values and a comparison function.
     * There's probably something I should use instead, but this was quick and
     * easy to build.
     * 
     */
    private class Coordinate {
        public int x;
        public int y;

        public Coordinate(int newX, int newY) {
            x = newX;
            y = newY;
        }

        public boolean equals(Coordinate other) {
            if (x == other.x && y == other.y) {
                return true;
            }
            return false;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }

        @Override
        public String toString() {
            return "Coordinate: [" + x + "," + y + "]";
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_DOWN)
        {

            if (mMode == READY ) {
                /*
                 * At the beginning of the game, or the end of a previous one,
                 * we should start a new game.
                 */
                 Log.d("Main","44444");
                MainActivity.score.setText(0+"");
                initNewGame();
                setMode(RUNNING);
                //update();
                MainActivity.layout.setVisibility(VISIBLE);
                Intent intent =new Intent(getContext(),GnamemusicService.class);
                getContext().startService(intent);
                return (true);
            }

//            if (mMode == PAUSE) {
//                /*
//                 * If the game is merely paused, we should just continue where
//                 * we left off.
//                 */
//                setMode(RUNNING);
//                update();
//                return (true);
//            }

//            if (mDirection != SOUTH) {
//                mNextDirection = NORTH;
//            }
            return (true);
        }
        return super.onTouchEvent(event);
    }
void showDialog()
{
     MygameApplication.mediaPlayer.pause();
    AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
    builder.setCancelable(false);
    if(oldertime==30) {
        if (mScore >= 8) {
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setMessage("本次游戏得到了" + mScore + "分" + "本局获得胜利");
        } else {

         builder.setIcon(R.mipmap.ic_launcher);
            builder.setMessage("本次游戏得到了"+mScore+"分"+"本局游戏失败");
        }

    }
    else if(oldertime==60)
    {
        if (mScore >= 18) {

            builder.setIcon(R.mipmap.ic_launcher);
            builder.setMessage("本次游戏得到了" + mScore + "分" + "本局获得胜利");


        } else {

            builder.setIcon(R.mipmap.ic_launcher);
            builder.setMessage("本次游戏得到了"+mScore+"分"+"本局游戏失败");
        }

    }
    else if(oldertime==90)
    {

        if (mScore >= 25) {

            builder.setIcon(R.mipmap.ic_launcher);
            builder.setMessage("本次游戏得到了" + mScore + "分" + "本局获得胜利");


        } else {

            builder.setIcon(R.mipmap.ic_launcher);
            builder.setMessage("本次游戏得到了"+mScore+"分"+"本局游戏失败");
        }
    }

    builder.setPositiveButton("下一局", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            ischoose=false;
            AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
            builder.setCancelable(false);
            builder.setTitle("请选择时间");
            builder.setSingleChoiceItems(items,0,new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ischoose=true;
                    item=which;
                  //Toast.makeText(getContext(),""+which,Toast.LENGTH_SHORT).show();
                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                       MygameApplication.mediaPlayer.start();
                   if(which==DialogInterface.BUTTON_POSITIVE)
                   {
                        if(!ischoose)
                            item=0;
                   }
                    if (item==0)
                    {
                        //intent.putExtra("item",30);
                        MainActivity.time=30;
                    }
                    else if(item==1)
                    {
                        //intent.putExtra("item",60);
                        MainActivity.time=60;
                    }else if(item==2)
                    {
                        //intent.putExtra("item",90);
                        MainActivity.time=90;
                    }
                    //startActivity(intent);
                    //新的一局游戏
                    if(MainActivity.timeText.getVisibility()==View.VISIBLE)
                    {
                        MainActivity.timeText.setVisibility(INVISIBLE);
                    }
                    if(mytask!=null)
                        mytask.cancel();
                    MainActivity.score.setText(0+"");
                    initNewGame();
                    setMode(RUNNING);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.main.finish();
                }
            });
            builder.show();
        }
    });
    builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            MainActivity.main.finish();
        }
    });
    builder.show();
}

}
